package live.betterman.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import live.betterman.system.dao.SysRoleMenuMapper;
import live.betterman.system.model.SysRoleMenu;
import live.betterman.system.model.SysUserRole;
import live.betterman.system.service.SysRoleMenuService;
import live.betterman.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhudawei
 * @since 2024-11-04
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {
    
    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public Collection<String> getMenus(String roleId) {
        if(StrUtil.isEmpty(roleId)){
            return Collections.emptySet();
        }
        return list(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId))
                .stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toSet());
    }

    @Override
    public boolean saveMenus(Collection<String> menuIds, String roleId) {
        remove(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId));
        
        if(!menuIds.isEmpty()){
            Set<SysRoleMenu> entities = menuIds.stream()
                    .map(menuId -> {
                        SysRoleMenu entity = new SysRoleMenu();
                        entity.setRoleId(roleId);
                        entity.setMenuId(menuId);
                        return entity;
                    })
                    .collect(Collectors.toSet());
            return saveBatch(entities);
        }
        return true;
    }

    @Override
    public Collection<String> getUserMenuIds(String userId) {
        Collection<SysUserRole> userRoles = userRoleService.getByUserId(userId);
        if(userRoles.isEmpty()) {
            return Collections.emptySet();
        }
        
        Collection<String> roleIds = userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toSet());
                
        return list(new LambdaQueryWrapper<SysRoleMenu>()
                .in(SysRoleMenu::getRoleId, roleIds))
                .stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toSet());
    }
}
